package com.jinzhi.jzweb.controller.moduleConfig;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.domain.ExaminationBatchComDO;
import com.jinzhi.jzweb.domain.ExaminationResultsComDO;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.domain.StuSignUpRequest;
import com.jinzhi.jzweb.domain.moduleConfig.*;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.pojo.StuSignUpComVo;
import com.jinzhi.jzweb.pojo.StuSignUpComVo2;
import com.jinzhi.jzweb.pojo.moduleConfig.CareStuSignUpComDownLoadVo;
import com.jinzhi.jzweb.pojo.moduleConfig.CareStuSignUpComRealityDownloadVo;
import com.jinzhi.jzweb.pojo.moduleConfig.CareStuSignUpComRealityVo;
import com.jinzhi.jzweb.service.ExaminationAnswerSheetComService;
import com.jinzhi.jzweb.service.ExaminationBatchComService;
import com.jinzhi.jzweb.service.ExaminationResultsComService;
import com.jinzhi.jzweb.service.StuSignUpComService;
import com.jinzhi.jzweb.service.moduleConfig.CareStuSignUpComRealityService;
import com.jinzhi.jzweb.service.moduleConfig.CityService;
import com.jinzhi.jzweb.service.moduleConfig.EncipherService;
import com.jinzhi.jzweb.service.moduleConfig.ProvincialService;
import com.jinzhi.jzweb.strategy.factory.PayStrategyFactory;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.SysUserRelevancyService;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 选手管理-制定照护计划 实际
 * </pre>
 * <small> 2023-05-05 08:52:02 | lance</small>downloadImportStu
 */
@Controller
@RequestMapping("/jzweb/careSignUpComReality")
@Api(value = "用户需求后台管理", tags = "用户需求后台管理")
public class StuSignUpComRealityController extends BaseController {
	private static final String IDCARD_PATTERN = "^(\\d{6})(18|19|20)\\d{2}(0[1-9]|1[012])(0[1-9]|[12]\\d|3[01])\\d{3}([0-9Xx])$";

	private final PayStrategyFactory payStrategyFactory;

	private final CareStuSignUpComRealityService careStuSignUpComRealityService;

	private final UserService userService;

	private final ExaminationBatchComService examinationBatchService;

	private final ExaminationAnswerSheetComService examinationAnswerSheetService;

	private final SysUserRelevancyService userRelevancyService;

	private final ExaminationResultsComService examinationResultsComService;

	private final EncipherService encipherService;

	private final StuSignUpComService stuSignUpComService;

	private final ProvincialService provincialService;

	private final CityService cityService;

	public StuSignUpComRealityController(PayStrategyFactory payStrategyFactory, CareStuSignUpComRealityService careStuSignUpComRealityService,UserService userService, ExaminationBatchComService examinationBatchService, ExaminationAnswerSheetComService examinationAnswerSheetService, SysUserRelevancyService userRelevancyService, ExaminationResultsComService examinationResultsComService,
										 EncipherService encipherService,StuSignUpComService stuSignUpComService,ProvincialService provincialService,CityService cityService) {
		this.payStrategyFactory = payStrategyFactory;
		this.careStuSignUpComRealityService = careStuSignUpComRealityService;
		this.userService = userService;
		this.examinationBatchService = examinationBatchService;
		this.examinationAnswerSheetService = examinationAnswerSheetService;
		this.userRelevancyService = userRelevancyService;
		this.examinationResultsComService = examinationResultsComService;
		this.encipherService = encipherService;
		this.stuSignUpComService = stuSignUpComService;
		this.provincialService = provincialService;
		this.cityService = cityService;
	}




//	@GetMapping()
//	@RequiresPermissions("jzweb:careSignUpComReality:careSignUpComReality")
//	String StuSignUpCom(Integer types,Model model){
//		model.addAttribute("types",types);
//	    return "jzweb/careSignUpComReality/careSignUpComReality";
//	}

	@GetMapping()
	@RequiresPermissions("jzweb:careSignUpComReality:careSignUpComReality")
	String StuSignUpCom(){
		return "jzweb/careSignUpComReality/careSignUpComReality";
	}


		/**
         * 第一次加密选手导出信息
         *
         * @param response
         */
	@GetMapping("/downloadImportStu")
	@RequiresPermissions("jzweb:careSignUpComReality:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response, CareStuSignUpComRealityDO stuSignUpComDTO) {
		stuSignUpComDTO.setCurrent(1);
		stuSignUpComDTO.setSize(999);
		List<CareStuSignUpComRealityDownloadVo> list = new ArrayList<>();
		List<CareStuSignUpComRealityDO> records = list(stuSignUpComDTO).getData().getRecords();
		for (CareStuSignUpComRealityDO record : records) {
			CareStuSignUpComRealityDownloadVo careStuSignUpComRealityDownloadVo = new CareStuSignUpComRealityDownloadVo();
			BeanUtils.copyProperties(record,careStuSignUpComRealityDownloadVo);
			list.add(careStuSignUpComRealityDownloadVo);
		}

		// 根据检录序号排序
		Comparator<CareStuSignUpComRealityDownloadVo> comparator = (careStuSignUpComRealityDownloadVo1, careStuSignUpComRealityDownloadVo2) -> {
			String recordNumber1 = careStuSignUpComRealityDownloadVo1.getRecordNumber();
			String recordNumber2 = careStuSignUpComRealityDownloadVo2.getRecordNumber();

			if (recordNumber1 == null && recordNumber2 == null) {
				return 0; // 如果两者都为空，则认为它们相等
			}

			if (recordNumber1 == null) {
				return -1; // 如果第一个为空，将其视为小于第二个（可按需调整）
			}

			if (recordNumber2 == null) {
				return 1; // 如果第二个为空，将其视为大于第一个（可按需调整）
			}

			try {
				return Integer.compare(Integer.parseInt(recordNumber1), Integer.parseInt(recordNumber2));
			} catch (NumberFormatException e) {
				throw new IllegalArgumentException("Invalid RecordNumber format", e);
			}
		};
		List<CareStuSignUpComRealityDownloadVo> sorted = list.stream()
				.sorted(comparator)
				.collect(Collectors.toList());
		EasyPoiUtil.exportExcel(sorted, "婴幼儿健康养育照护知识测评报名信息", "婴幼儿健康养育照护知识测评报名信息", CareStuSignUpComRealityDownloadVo.class, "婴幼儿健康养育照护知识测评报名信息", response);
	}


	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:careSignUpComReality:careSignUpComReality")
	public Result<Page<CareStuSignUpComRealityDO>> list(CareStuSignUpComRealityDO stuSignUpComDTO){
		Page<CareStuSignUpComRealityDO> careStuSignUpComRealityDOPage = new Page<>(stuSignUpComDTO.getCurrent(),stuSignUpComDTO.getSize());

		Wrapper<CareStuSignUpComRealityDO> wrapper=new EntityWrapper<>();

		if(StringUtils.isNotBlank(stuSignUpComDTO.getName())){
			wrapper.like("name",stuSignUpComDTO.getName());
		}
		if(StringUtils.isNotBlank(stuSignUpComDTO.getCbatchName())){
			ExaminationBatchComDO examinationBatchComDO1=	examinationBatchService.findOneByKv("name",stuSignUpComDTO.getCbatchName());
			if(examinationBatchComDO1!=null){
				wrapper.like("cbatch_id",examinationBatchComDO1.getId().toString());
			}

		}
		// 查询列表数据
		Page<CareStuSignUpComRealityDO> page = careStuSignUpComRealityService.selectPage(careStuSignUpComRealityDOPage,wrapper);

		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				CareStuSignUpComRealityDO obj = (CareStuSignUpComRealityDO) page.getRecords().get(i);
			ExaminationBatchComDO examinationBatchComDO=examinationBatchService.selectById(obj.getCbatchId());
			if(examinationBatchComDO!=null){
				obj.setCbatchName(examinationBatchComDO.getName());
			}
			obj.setProvince(obj.getProvince()+","+obj.getCity());
			Wrapper<EncipherDO> doWrapper = new EntityWrapper<EncipherDO>().eq("stu_id", page.getRecords().get(i).getId()).eq("field", "C");
			List<EncipherDO> encipherDOS = encipherService.selectList(doWrapper);
			if(null!=encipherDOS && !encipherDOS.isEmpty()){
				page.getRecords().get(i).setNum1(encipherDOS.get(0).getNum1()!=null?encipherDOS.get(0).getNum1():null);
				page.getRecords().get(i).setNum2(encipherDOS.get(0).getNum2()!=null?encipherDOS.get(0).getNum2():null);
			}else{
				page.getRecords().get(i).setNum1(null);
				page.getRecords().get(i).setNum2(null);
			}

			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:careSignUpComReality:add")
	String add(){

	    return "jzweb/careSignUpComReality/add";
	}


	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:careSignUpComReality:edit")
	String edit(@PathVariable("id") Long id,Model model){
		CareStuSignUpComRealityDO stuSignUpCom = careStuSignUpComRealityService.selectById(id);
		//通过学校查询两名选手信息
		/*List<CareStuSignUpComRealityDO> careStuSignUpComRealityDOS = careStuSignUpComRealityService.selectList(new EntityWrapper<CareStuSignUpComRealityDO>().eq("unit_name", stuSignUpCom.getUnitName()));
		if(null!=careStuSignUpComRealityDOS && !careStuSignUpComRealityDOS.isEmpty()){
			stuSignUpCom = careStuSignUpComRealityDOS.get(0);
			CareStuSignUpComRealityDO careStuSignUpComRealityDO = careStuSignUpComRealityDOS.get(1);
			String name2 = careStuSignUpComRealityDO.getName();
			String nation2 = careStuSignUpComRealityDO.getNation();
			String sex2 = careStuSignUpComRealityDO.getSex();
			String idNumber2 = careStuSignUpComRealityDO.getIdNumber();
			String ticketNumber2 = careStuSignUpComRealityDO.getTicketNumber();
			stuSignUpCom.setName2(name2);
			stuSignUpCom.setNation2(nation2);
			stuSignUpCom.setIdNumber2(idNumber2);
			stuSignUpCom.setSex2(sex2);
			stuSignUpCom.setTicketNumber2(ticketNumber2);

		}*/
		model.addAttribute("stuSignUpCom", stuSignUpCom);
		return "jzweb/careSignUpComReality/edit";
	}


	@Log("添加考生报名")
	@ResponseBody
	@PostMapping("/save")
	@Transactional
	@RequiresPermissions("jzweb:careSignUpComReality:add")
	public Result<String> save( CareStuSignUpComRealityDO careStuSignUpComRealityDO){
		if(null==careStuSignUpComRealityDO.getPid()){
			return Result.fail("请选择省份信息！");
		}
		if(null==careStuSignUpComRealityDO.getCid()){
			return Result.fail("请选择市信息！");
		}
		ProvincialDO provincialDO = provincialService.selectById(careStuSignUpComRealityDO.getPid());
		CityDO cityDO = cityService.selectById(careStuSignUpComRealityDO.getCid());
		if(null!=provincialDO){
			careStuSignUpComRealityDO.setProvince(provincialDO.getProvincial());
		}
		if(null!=cityDO){
			careStuSignUpComRealityDO.setCity(cityDO.getCity());
		}
		//学校不能为空
		if(null==careStuSignUpComRealityDO.getUnitName()){
			return Result.fail("请输入参赛单位！");
		}
		//校验身份证号码
		Pattern pattern = Pattern.compile(IDCARD_PATTERN);
		if(careStuSignUpComRealityDO.getIdNumber()!=null){
			if(!pattern.matcher(careStuSignUpComRealityDO.getIdNumber()).matches()){
				return Result.fail("身份证:"+careStuSignUpComRealityDO.getIdNumber()+"格式不对！");
			}
		}
		if(careStuSignUpComRealityDO.getIdNumber2()!=null){
			if(!pattern.matcher(careStuSignUpComRealityDO.getIdNumber2()).matches()){
				return Result.fail("身份证:"+careStuSignUpComRealityDO.getIdNumber2()+"格式不对！");
			}
		}

		//学校不能相同
		List<CareStuSignUpComRealityDO> careStuSignUpComRealityDOS = careStuSignUpComRealityService.selectList(new EntityWrapper<CareStuSignUpComRealityDO>().eq("unit_name", careStuSignUpComRealityDO.getUnitName()));
		if(careStuSignUpComRealityDOS!=null && !careStuSignUpComRealityDOS.isEmpty()){
			return Result.fail("参赛单位已经报名！");
		}


		//查询最近的竞赛 ： 制定照护计划和职业素养测评
		//查询时间最早的制定照护计划
		Page<ExaminationBatchComDO> page = new Page<>(1,1);
		/*Wrapper<ExaminationBatchComDO> wrapper1 = new EntityWrapper<ExaminationBatchComDO>().eq("type",1).orderBy("start_time", false);
		List<ExaminationBatchComDO> records = examinationBatchService.selectPage(page, wrapper1).getRecords();
		if(null==records || records.isEmpty()){
			return Result.fail("请先创建类型为制定照护计划的竞赛");
		}
		ExaminationBatchComDO examinationBatchComDO1 = records.get(0);
		Long ebatchId1 = examinationBatchComDO1.getId();*/

		Wrapper<ExaminationBatchComDO> wrapper2 = new EntityWrapper<ExaminationBatchComDO>().eq("type",2).orderBy("start_time", false);
		List<ExaminationBatchComDO> records2 = examinationBatchService.selectPage(page, wrapper2).getRecords();
		if(null==records2 || records2.isEmpty()){
			return Result.fail("请先创建类型为职业素养测评的竞赛");
		}
		ExaminationBatchComDO examinationBatchComDO2 = records2.get(0);
		Long ebatchId2 = examinationBatchComDO2.getId();

		careStuSignUpComRealityDO.setState(3);
//		if(stuSignUpCom.getTypes()==3){
//			stuSignUpCom.setCourt("A");
//		}

		//获取竞赛编号和考试编号
		/*Integer maxNum1=careStuSignUpComRealityService.MaxNum(ebatchId1);
		if(maxNum1==null){
			maxNum1=0;
		}
		Integer nums1 = maxNum1+1;
		String comName1 = examinationBatchComDO1.getCompetitionName()+"00"+nums1;*/

		//Integer maxNum2=careStuSignUpComRealityService.MaxNum(ebatchId2);
		Integer maxNum2=careStuSignUpComRealityService.MaxNum(null);
		if(maxNum2==null){
			maxNum2=0;
		}
		Integer nums2 = maxNum2;
		//String comName2 = examinationBatchComDO2.getCompetitionName()+"00"+nums2;
		nums2+=1;
		careStuSignUpComRealityDO.setSignUpTime(new Date());
		careStuSignUpComRealityDO.setCompetitionType(1);
		careStuSignUpComRealityDO.setCbatchId(ebatchId2);
		careStuSignUpComRealityDO.setComNum(nums2);
		careStuSignUpComRealityDO.setComNums(examinationBatchComDO2.getCompetitionName()+"00"+nums2);
		careStuSignUpComRealityService.insert(careStuSignUpComRealityDO);

		//同步到虚拟选手管理 一位实际选手职业素养测评
		StuSignUpComDO stuSignUpComDO = new StuSignUpComDO();
		BeanUtils.copyProperties(careStuSignUpComRealityDO,stuSignUpComDO);
		/*stuSignUpComDO.setId(null);
		stuSignUpComService.insert(stuSignUpComDO);*/
		stuSignUpComDO.setId(null);
		stuSignUpComDO.setCompetitionType(2);
		stuSignUpComDO.setCbatchId(ebatchId2);
		stuSignUpComDO.setComNum(nums2);
		stuSignUpComDO.setComNums(examinationBatchComDO2.getCompetitionName()+"00"+nums2);
		//stuSignUpComDO.setComNums(comName2);
		stuSignUpComService.insert(stuSignUpComDO);

		//添加第二位选手
		/*if(null!=careStuSignUpComRealityDO.getName2()){
			getStuInfo(careStuSignUpComRealityDO, careStuSignUpComRealityDO);

			careStuSignUpComRealityDO.setId(null);
			careStuSignUpComRealityDO.setCbatchId(ebatchId2);
			careStuSignUpComRealityDO.setCompetitionType(2);
			careStuSignUpComRealityDO.setComNum(nums2);
			careStuSignUpComRealityDO.setComNums(comName2);
			careStuSignUpComRealityService.insert(careStuSignUpComRealityDO);

			BeanUtils.copyProperties(careStuSignUpComRealityDO,stuSignUpComDO);
			stuSignUpComDO.setId(null);
			stuSignUpComService.insert(stuSignUpComDO);
			stuSignUpComDO.setId(null);
			stuSignUpComDO.setCompetitionType(1);
			stuSignUpComDO.setCbatchId(ebatchId1);
			stuSignUpComDO.setComNum(nums1);
			stuSignUpComDO.setComNums(comName1);
			stuSignUpComService.insert(stuSignUpComDO);

		}*/

		return Result.ok();
	}


	@Log("修改考生报名")
	@ResponseBody
	@Transactional
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:careSignUpComReality:edit")
	public Result<String>  update( CareStuSignUpComRealityDO stuSignUpCom){
		if(null==stuSignUpCom.getPid()){
			return Result.fail("请选择省份信息！");
		}
		if(null==stuSignUpCom.getCid()){
			return Result.fail("请选择市信息！");
		}
		ProvincialDO provincialDO = provincialService.selectById(stuSignUpCom.getPid());
		CityDO cityDO = cityService.selectById(stuSignUpCom.getCid());
		if(null!=provincialDO){
			stuSignUpCom.setProvince(provincialDO.getProvincial());
		}
		if(null!=cityDO){
			stuSignUpCom.setCity(cityDO.getCity());
		}

		//学校不能为空
		if(null==stuSignUpCom.getUnitName()){
			return Result.fail("请输入参赛单位！");
		}
		//校验身份证号码
		Pattern pattern = Pattern.compile(IDCARD_PATTERN);
		if(stuSignUpCom.getIdNumber()!=null){
			if(!pattern.matcher(stuSignUpCom.getIdNumber()).matches()){
				return Result.fail("身份证:"+stuSignUpCom.getIdNumber()+"格式不对！");
			}
		}
		if(stuSignUpCom.getIdNumber2()!=null){
			if(!pattern.matcher(stuSignUpCom.getIdNumber2()).matches()){
				return Result.fail("身份证:"+stuSignUpCom.getIdNumber2()+"格式不对！");
			}
		}

		//学校不能相同
		List<CareStuSignUpComRealityDO> careStuSignUpComRealityList = careStuSignUpComRealityService.selectList(new EntityWrapper<CareStuSignUpComRealityDO>().eq("unit_name", stuSignUpCom.getUnitName()));
		if(careStuSignUpComRealityList!=null && !careStuSignUpComRealityList.isEmpty() && careStuSignUpComRealityList.size()>1){
			boolean flag = false;
			for (CareStuSignUpComRealityDO careStuSignUpComRealityDO : careStuSignUpComRealityList) {
				if(careStuSignUpComRealityDO.getId().toString().equals(stuSignUpCom.getId().toString())){
					flag = true;
					break;
				}
			}
			if(!flag){
				return Result.fail("参赛单位已经报名！");
			}
		}

		//需要修改两条数据
		CareStuSignUpComRealityDO careStuSignUpComRealityDO = careStuSignUpComRealityService.selectById(stuSignUpCom.getId());
		List<CareStuSignUpComRealityDO> careStuSignUpComRealityDOS = careStuSignUpComRealityService.selectList(new EntityWrapper<CareStuSignUpComRealityDO>().eq("unit_name", careStuSignUpComRealityDO.getUnitName()));
		//通过学校查询两名选手信息
//		boolean update = careStuSignUpComRealityService.updateById(stuSignUpCom);
		stuSignUpCom.setId(null);
		CareStuSignUpComRealityDO careStuSignUpComRealityDO1 = careStuSignUpComRealityDOS.get(0);
		//CareStuSignUpComRealityDO careStuSignUpComRealityDO2 = careStuSignUpComRealityDOS.get(1);
		//存储选手信息和单位信息 用于修改
		String unitName1 = careStuSignUpComRealityDO1.getUnitName();
		//String unitName2 = careStuSignUpComRealityDO2.getUnitName();
		String name1 = careStuSignUpComRealityDO1.getName();
		//String name2 = careStuSignUpComRealityDO2.getName();
		Long id1 = careStuSignUpComRealityDO1.getId();
		//Long id2 = careStuSignUpComRealityDO2.getId();
		BeanUtils.copyProperties(stuSignUpCom,careStuSignUpComRealityDO1);
		//BeanUtils.copyProperties(stuSignUpCom,careStuSignUpComRealityDO2);
		//getStuInfo(stuSignUpCom, careStuSignUpComRealityDO2);
		careStuSignUpComRealityDO1.setId(id1);
		//careStuSignUpComRealityDO2.setId(id2);
		careStuSignUpComRealityService.updateById(careStuSignUpComRealityDO1);
		//careStuSignUpComRealityService.updateById(careStuSignUpComRealityDO2);

		//修改虚拟选手

		StuSignUpComDO stuSignUpComDO = new StuSignUpComDO();
		BeanUtils.copyProperties(careStuSignUpComRealityDO1,stuSignUpComDO);
		stuSignUpComDO.setId(null);
		stuSignUpComService.update(stuSignUpComDO,new EntityWrapper<StuSignUpComDO>().eq("unit_name",unitName1).eq("name",name1));

//		stuSignUpComDO.setId(null);
//		BeanUtils.copyProperties(careStuSignUpComRealityDO2,stuSignUpComDO);
//		stuSignUpComService.update(stuSignUpComDO,new EntityWrapper<StuSignUpComDO>().eq("unit_name",unitName2).eq("name",name2));

		return  Result.ok();
	}

	private void getStuInfo(CareStuSignUpComRealityDO stuSignUpCom, CareStuSignUpComRealityDO careStuSignUpComRealityDO2) {
		String name2 = stuSignUpCom.getName2();
		String nation2 = null==stuSignUpCom.getNation2()?"-":stuSignUpCom.getNation2();
		String sex2 = null==stuSignUpCom.getSex2()?"-":stuSignUpCom.getSex2();
		String idNumber2 = null== stuSignUpCom.getIdNumber2()?"-":stuSignUpCom.getIdNumber2();
		String ticketNumber2 = null==stuSignUpCom.getTicketNumber2()?"-":stuSignUpCom.getTicketNumber2();
		careStuSignUpComRealityDO2.setName(name2);
		careStuSignUpComRealityDO2.setNation(nation2);
		careStuSignUpComRealityDO2.setIdNumber(idNumber2);
		careStuSignUpComRealityDO2.setSex(sex2);
		careStuSignUpComRealityDO2.setTicketNumber(ticketNumber2);
	}

	@Log("删除考生报名")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:careSignUpComReality:remove")
	public Result<String>  remove( Long id){
		//同步删除选手虚拟信息
		CareStuSignUpComRealityDO careStuSignUpComRealityDO = careStuSignUpComRealityService.selectById(id);
		if(null!=careStuSignUpComRealityDO){
			stuSignUpComService.delete(new EntityWrapper<StuSignUpComDO>().eq("unit_name",careStuSignUpComRealityDO.getUnitName()));

			careStuSignUpComRealityService.delete(new EntityWrapper<CareStuSignUpComRealityDO>().eq("unit_name",careStuSignUpComRealityDO.getUnitName()));
		}

		return Result.ok();
	}
	
	@Log("批量删除考生报名")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:careSignUpComReality:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		for (Long id : ids) {
			//同步删除选手虚拟信息
			CareStuSignUpComRealityDO careStuSignUpComRealityDO = careStuSignUpComRealityService.selectById(id);
			if(null!=careStuSignUpComRealityDO){
				stuSignUpComService.delete(new EntityWrapper<StuSignUpComDO>().eq("unit_name",careStuSignUpComRealityDO.getUnitName()));

				careStuSignUpComRealityService.delete(new EntityWrapper<CareStuSignUpComRealityDO>().eq("unit_name",careStuSignUpComRealityDO.getUnitName()));
			}
		}

		return Result.ok();
	}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importComError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:careSignUpComReality:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考生报名导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("stuSignComUp" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}


	/**
	 * 导如模板 信息
	 * @throws Exception
	 */
	@GetMapping("/exportList")
	@ResponseBody
	public void exportlist( HttpServletRequest request, HttpServletResponse responseexa) throws Exception{

		List<CareStuSignUpComRealityVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "实际选手导入模板", "实际选手导入模板", CareStuSignUpComRealityVo.class, "实际选手导入模板", responseexa);

	}


	/**
	 * 考生信息导入
	 *
	 * @param file excel文件
	 */
	@Log("考生信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:careSignUpComReality:import")
	public Result<?> importExcel(HttpServletRequest req, @RequestParam("file") MultipartFile file) {
		//---------------------------------检测导入信息及条件-----------------------------------------
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<CareStuSignUpComRealityVo> list = EasyPoiUtil.importExcel(file, 1, 1, CareStuSignUpComRealityVo.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}


		//第四步--判断该认证批次是否已经建立了理论考试批次；
		//todo 目前定义为只要是认证批次，就一定存在理论考试
		//查询最近的竞赛 ： 制定照护计划和职业素养测评
		//查询时间最早的制定照护计划
		Page<ExaminationBatchComDO> page = new Page<>(1,1);
		/*Wrapper<ExaminationBatchComDO> wrapper1 = new EntityWrapper<ExaminationBatchComDO>().eq("type",1).orderBy("start_time", false);
		List<ExaminationBatchComDO> records = examinationBatchService.selectPage(page, wrapper1).getRecords();
		if(null==records || records.isEmpty()){
			return Result.fail("请先创建类型为制定照护计划的竞赛");
		}
		ExaminationBatchComDO examinationBatchComDO1 = records.get(0);
		Long ebatchId1 = examinationBatchComDO1.getId();*/

		Wrapper<ExaminationBatchComDO> wrapper2 = new EntityWrapper<ExaminationBatchComDO>().eq("type",2).orderBy("start_time", false);
		List<ExaminationBatchComDO> records2 = examinationBatchService.selectPage(page, wrapper2).getRecords();
		if(null==records2 || records2.isEmpty()){
			return Result.fail("请先创建类型为职业素养测评的竞赛");
		}
		ExaminationBatchComDO examinationBatchComDO2 = records2.get(0);
		Long ebatchId2 = examinationBatchComDO2.getId();

		//获取竞赛编号和考试编号
		/*Integer maxNum1=careStuSignUpComRealityService.MaxNum(ebatchId1);
		if(maxNum1==null){
			maxNum1=0;
		}
		Integer nums1 = maxNum1+1;
		String comName1 = examinationBatchComDO1.getCompetitionName()+"00"+nums1;*/

		Integer maxNum2=careStuSignUpComRealityService.MaxNum(null);
		if(maxNum2==null){
			maxNum2=0;
		}
		Integer nums2 = maxNum2;
		//String comName2 = examinationBatchComDO2.getCompetitionName()+"00"+nums2;

		//---------------------------------验证数据并导入-----------------------------------------
		//数据该市行为第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<CareStuSignUpComRealityDO> upDOList = new LinkedList<>();
		List<ErrorCodeVo> list1 = new LinkedList<>();
		for (int i = 0; i < list.size(); i++) {
			UserDO rrUserDo = null;
			UserDO rsUserDo = null;
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值
			if (StringUtils.isBlank(list.get(i).getUnitName())) {
				sb.append("第" + (i + startRow) + "行参赛单位未填写，请完善！" + ";");
			} else {
				if (StringUtils.isBlank(list.get(i).getProvince())) {
					sb.append("第" + (i + startRow) + "行省份信息未填写，请完善！" + ";");
				}else{
					if (StringUtils.isBlank(list.get(i).getTeamLeader())) {
						sb.append("第" + (i + startRow) + "行领队未填写，请完善！" + ";");
					} else {
						if (StringUtils.isBlank(list.get(i).getTeacher())) {
							sb.append("第" + (i + startRow) + "行指导老师未填写，请完善！" + ";");
						}else {
							if (StringUtils.isBlank(list.get(i).getName())) {
								sb.append("第" + (i + startRow) + "行选手姓名未填写，请完善！" + ";");
							} else {
								if (StringUtils.isBlank(list.get(i).getSex())) {
									sb.append("第" + (i + startRow) + "行性别未填写，请完善！" + ";");
								} else {
									if (StringUtils.isBlank(list.get(i).getNation())) {
										sb.append("第" + (i + startRow) + "行民族未填写，请完善！" + ";");
									} else {
										if (StringUtils.isBlank(list.get(i).getIdNumber())) {
											sb.append("第" + (i + startRow) + "行身份证号码未填写，请完善！" + ";");
										} else {
											if (StringUtils.isBlank(list.get(i).getTicketNumber())) {
												sb.append("第" + (i + startRow) + "行联系方式未填写，请完善！" + ";");
											} else {
												//校验身份证号码
												Pattern pattern = Pattern.compile(IDCARD_PATTERN);
												if(list.get(i).getIdNumber()!=null){
													if(!pattern.matcher(list.get(i).getIdNumber()).matches()){
														//return Result.fail("身份证:"+list.get(i).getIdNumber()+"格式不对！");
														sb.append("第" + (i + startRow) + "行身份证号码格式不正确，请完善！" + ";");
													}
												}
											}
										}
									}
								}
							}

							if (sb.length() == 0) {
								//第四步排重验证（自身比较）
//								for (int j = 0; j < list.size(); j++) {
//									if (i != j) {
//										if (list.get(i).getTicketNumber().equals(list.get(j).getTicketNumber())) {
//											sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行准考证号重复，重复值：" + list.get(i).getIdNumber() + ";");
//										}
//									}
//								}

								//第六步排重验证（和数据库比较），根据考生名称、考生身份证号码、该场考试的认证批次判断该考生是否已报名该考试
								/*CareStuSignUpComRealityDO stuSignUpDO = careStuSignUpComRealityService.findOneByKv("name", list.get(i).getName(), "id_number", list.get(i).getIdNumber(), "cbatch_id", ebatchId1);
								if (stuSignUpDO != null) {
									sb.append("第" + (i + startRow) + "行考生已报名该次考试！" + ";");
								}*/
								CareStuSignUpComRealityDO stuSignUpDO2 = careStuSignUpComRealityService.findOneByKv("name", list.get(i).getName(), "id_number", list.get(i).getIdNumber(), "cbatch_id", ebatchId2);
								if (stuSignUpDO2 != null) {
									sb.append("第" + (i + startRow) + "行考生已报名该次考试！" + ";");
								}

							}

						}
					}
				}

			}

			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				cout += 1;
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
			} else {
				if (rrUserDo != null) {
					boolean cc = userService.insertNoPW(rrUserDo);
					if (!cc) {
					}
				}
			}


			CareStuSignUpComRealityDO stuSignUpDO1 = new CareStuSignUpComRealityDO();
			BeanUtils.copyProperties(list.get(i),stuSignUpDO1);
			stuSignUpDO1.setName(list.get(i).getName());//姓名
			stuSignUpDO1.setIdNumber(list.get(i).getIdNumber());//身份证号码
			stuSignUpDO1.setSignUpTime(new Date());//报名时间
			stuSignUpDO1.setDecrypt(0);
			stuSignUpDO1.setType(0);
			stuSignUpDO1.setState(3);//默认已分配
			stuSignUpDO1.setTeamLeader(list.get(i).getTeamLeader());
			stuSignUpDO1.setUnitName(list.get(i).getUnitName());

			stuSignUpDO1.setTicketNumber(list.get(i).getTicketNumber());//考号

			stuSignUpDO1.setCheckerId(this.getUserId());//默认审核人为导入者
			stuSignUpDO1.setCheckerDate(new Date());//默认审核时间为导入时间
			upDOList.add(stuSignUpDO1);

		}

		if (list1.size() == 0) {
			List<CareStuSignUpComRealityDO> groupList = new LinkedList<>();//实际选手信息
			List<StuSignUpComDO> signList = new LinkedList<>();//虚拟选手信息
			// 使用Stream API按照unitName进行分组
			Map<String, List<CareStuSignUpComRealityDO>> groupMap = upDOList.stream()
					.collect(Collectors.groupingBy(CareStuSignUpComRealityDO::getUnitName));
			//groupMap.forEach((unitName, items) -> {
			for (Map.Entry<String, List<CareStuSignUpComRealityDO>> entry : groupMap.entrySet()) {
				String unitName = entry.getKey();
				List<CareStuSignUpComRealityDO> items = entry.getValue();
				//只考虑一个学校两名选手的情况
				if(items.size()==1){
					//处理省市 已逗号分割
					String[] strings = items.get(0).getProvince().split(",");
					//处理一下省市
					List<ProvincialDO> provincialList = provincialService.selectList(new EntityWrapper<ProvincialDO>().like("provincial", strings[0]));
					if(null!=provincialList && !provincialList.isEmpty()){
						items.get(0).setProvince(provincialList.get(0).getProvincial());
						items.get(0).setPid(String.valueOf(provincialList.get(0).getPid()));
						/*items.get(1).setProvince(provincialList.get(0).getProvincial());
						items.get(1).setPid(String.valueOf(provincialList.get(0).getPid()));*/
					}
					List<CityDO> cityList = cityService.selectList(new EntityWrapper<CityDO>().like("city", strings[1]));
					if(null!=cityList && !cityList.isEmpty()){
						items.get(0).setCity(cityList.get(0).getCity());
						items.get(0).setCid(String.valueOf(cityList.get(0).getCid()));
						/*items.get(1).setCity(cityList.get(0).getCity());
						items.get(1).setCid(String.valueOf(cityList.get(0).getCid()));*/
					}
					//处理一下民族
					String nation = items.get(0).getNation();
					if(!nation.contains("族")){
						items.get(0).setNation(nation + "族");
					}

					/*CareStuSignUpComRealityDO careStuSignUpComRealityDO1 = items.get(0);
					careStuSignUpComRealityDO1.setCompetitionType(1);
					careStuSignUpComRealityDO1.setCbatchId(ebatchId1);
					careStuSignUpComRealityDO1.setComNum(nums1);
					careStuSignUpComRealityDO1.setComNums(comName1);
					groupList.add(careStuSignUpComRealityDO1);*/

					//处理竞赛编号
					nums2+=1;
					String comName2 = examinationBatchComDO2.getCompetitionName()+"00"+nums2;
					CareStuSignUpComRealityDO careStuSignUpComRealityDO2 = items.get(0);
					careStuSignUpComRealityDO2.setCompetitionType(2);
					careStuSignUpComRealityDO2.setCbatchId(ebatchId2);
					careStuSignUpComRealityDO2.setComNum(nums2);
					careStuSignUpComRealityDO2.setComNums(examinationBatchComDO2.getCompetitionName()+"00"+nums2);
					groupList.add(careStuSignUpComRealityDO2);

					//一位选手既要参加制定照护计划，也要参加职业素养测评
					StuSignUpComDO stuSignUpComDO1 = new StuSignUpComDO();
					BeanUtils.copyProperties(careStuSignUpComRealityDO2,stuSignUpComDO1);
					signList.add(stuSignUpComDO1);
					/*StuSignUpComDO stuSignUpComDO2 = new StuSignUpComDO();
					BeanUtils.copyProperties(careStuSignUpComRealityDO2,stuSignUpComDO2);
					stuSignUpComDO2.setCompetitionType(2);
					stuSignUpComDO2.setCbatchId(ebatchId2);
					stuSignUpComDO2.setComNum(nums2);
					stuSignUpComDO2.setComNums(comName2);
					signList.add(stuSignUpComDO2);*/

					/*StuSignUpComDO stuSignUpComDO3 = new StuSignUpComDO();
					BeanUtils.copyProperties(careStuSignUpComRealityDO2,stuSignUpComDO3);
					signList.add(stuSignUpComDO3);
					StuSignUpComDO stuSignUpComDO4 = new StuSignUpComDO();
					BeanUtils.copyProperties(careStuSignUpComRealityDO2,stuSignUpComDO4);
					stuSignUpComDO4.setCompetitionType(1);
					stuSignUpComDO4.setCbatchId(ebatchId1);
					stuSignUpComDO4.setComNum(nums1);
					stuSignUpComDO4.setComNums(comName1);
					signList.add(stuSignUpComDO4);*/

				}
			}
			boolean c = careStuSignUpComRealityService.insertBatch(groupList, groupList.size());
			stuSignUpComService.insertBatch(signList,signList.size());
			if (c) {
				return Result.ok("成功导入" + list.size() + "条数据");
			} else {

				return Result.fail("报名信息导入错误，请稍后重试或联系管理员");
			}
		} else {

			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("stuSignComUp" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
	}

}
